﻿using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Dest.Math;
//此脚本挂在一个全屏并且透明的Image上
public class RangeSelect : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
    MeshRenderer[] cubes;
    public Image image;
    Vector3 startPos;
    Vector3 endPos;
    Camera cam;
    AAB2 aAB2 = new AAB2();
    private void Start()
    {
        cubes = FindObjectsOfType<MeshRenderer>();
        cam = Camera.main;
    }


    public void OnBeginDrag(PointerEventData eventData)
    {
        image.gameObject.SetActive(true);
        image.rectTransform.sizeDelta = new Vector2(1, 1);
        image.transform.position = eventData.position;
        startPos = eventData.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        endPos = eventData.position;
        //设置锚点,解决选区图片长款为负后不显示的问题
        Vector2 pivot = new Vector2(startPos.x > endPos.x ? 1 : 0, startPos.y > endPos.y ? 1 : 0);
        image.rectTransform.pivot = pivot;
        //显示选取
        image.rectTransform.sizeDelta = new Vector2(Mathf.Abs(endPos.x - startPos.x), Mathf.Abs(endPos.y - startPos.y));
        //设置AAB2的范围
        aAB2.Min = new Vector2(Mathf.Min(startPos.x, endPos.x), Mathf.Min(startPos.y, endPos.y));
        aAB2.Max = new Vector2(Mathf.Max(startPos.x, endPos.x), Mathf.Max(startPos.y, endPos.y));
        //判断是所有顶点都否在范围内
        for (int i = 0; i < cubes.Length; i++)
        {
            Transform tf = cubes[i].transform;
            Vector3[] verticals = tf.GetComponent<MeshFilter>().mesh.vertices;
            bool inRange = true;
            for (int j = 0; j < verticals.Length; j++)
            {
                Vector3 screenPos = cam.WorldToScreenPoint(tf.position + verticals[j]);
                if (!aAB2.Contains(screenPos))
                {
                    inRange = false;
                    break;
                }
            }
            tf.GetComponent<MeshRenderer>().material.color = inRange ? Color.red : Color.white;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        image.gameObject.SetActive(false);
    }
}
